package com.mall.controller;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.mall.common.WebResult;
import com.mall.common.WebResultHelper;
import com.mall.vo.UploadImgVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/system")
public class UploadImgController extends BaseController {

	@Autowired
	private OSSClient ossClient;
	
	/**
	 * 上传图片
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/uploadImage")
	public WebResult<UploadImgVO> uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request)
			throws Exception {
		UploadImgVO uploadImgInfo = new UploadImgVO();
		try {
			// 原文件名称
			String trueName = file.getOriginalFilename();
			// 文件后缀名
			String ext = trueName.substring((trueName.lastIndexOf(".")+1),trueName.length()).toLowerCase();
			// 系统生成的文件名
			String fileName = file.getOriginalFilename();
			
			String winRoot = env.getProperty("file.upload.win.root");
			String linuxRoot = env.getProperty("file.upload.linux.root");
			String uploadPath = env.getProperty("file.upload.img.path");
			if(!this.checkIconType(trueName)){//视频
				uploadPath = env.getProperty("file.upload.video.path");
			}
			String nginxImg = "this.getBaseImgUrl()";
			String upload_dir_path = "";
			String dbSavePath = "";
//			if (IpUtil.isWindows()) {// windows系统
//				upload_dir_path = winRoot + uploadPath;
//			} else {// 其他系统
//				upload_dir_path = linuxRoot + uploadPath;
//			}
			String currentMonth = DateUtil.format(new Date(), "yyyy-MM");
			upload_dir_path = upload_dir_path + "/" + currentMonth;
			dbSavePath = uploadPath + "/" + currentMonth;
			File imgDirFile = new File(upload_dir_path);
			if (!imgDirFile.exists()) {
				imgDirFile.mkdirs();
			}

			fileName = System.currentTimeMillis() + new Random().nextInt(10000) + "." + ext;
			String upload_img = upload_dir_path + "/" + fileName;
			String db_save_img = dbSavePath + "/" + fileName;
			File saveFile = new File(upload_img);
			file.transferTo(saveFile);

			uploadImgInfo.setImgName(trueName);
			uploadImgInfo.setImgPath(upload_img);
			uploadImgInfo.setImgCallPath(db_save_img);
			uploadImgInfo.setImgSrcUrl(nginxImg + db_save_img);
			
		} catch (Exception e) {

		}
		return WebResultHelper.success(uploadImgInfo, "上传成功！");
	}
	
	/**
	 * 富文本框上传图片
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/uploadImageByUmeditor")
	public Map<String,Object> uploadImageByUmeditor(@RequestParam("file") MultipartFile file, HttpServletRequest request)
			throws Exception {
		Map<String,Object> map = new HashMap<>();
		try {
			String winRoot = env.getProperty("file.upload.win.root");
			String linuxRoot = env.getProperty("file.upload.linux.root");
			String uploadPath = env.getProperty("file.upload.img.path");
			String nginxImg = "";
			String upload_dir_path = "";
			String dbSavePath = "";
//			if (IpUtil.isWindows()) {// windows系统
//				upload_dir_path = winRoot + uploadPath;
//			} else {// 其他系统
//				upload_dir_path = linuxRoot + uploadPath;
//			}
			String currentMonth = DateUtil.format(new Date(), "yyyy-MM");
			upload_dir_path = upload_dir_path + "/" + currentMonth;
			dbSavePath = uploadPath + "/" + currentMonth;
			File imgDirFile = new File(upload_dir_path);
			if (!imgDirFile.exists()) {
				imgDirFile.mkdirs();
			}
			// 原文件名称
			String trueName = file.getOriginalFilename();
			// 文件后缀名
			String ext = trueName.substring((trueName.lastIndexOf(".")+1),trueName.length()).toLowerCase();
			// 系统生成的文件名
			String fileName = file.getOriginalFilename();
			fileName = System.currentTimeMillis() + new Random().nextInt(10000) + "." + ext;
			String upload_img = upload_dir_path + "/" + fileName;
			String db_save_img = dbSavePath + "/" + fileName;
			File saveFile = new File(upload_img);
			file.transferTo(saveFile);
			map.put("url",nginxImg + db_save_img);
			map.put("state", "SUCCESS");
		} catch (Exception e) {
		}
		return map;
	}
	

//	@SuppressWarnings({ "unchecked", "deprecation" })
//	@RequestMapping(path = "/sts_oss_key", method = { RequestMethod.GET })
//	@ResponseBody
//	public AppResult sts_oss_key() {
//		AppResult app = new AppResult<>(OK);
//		String endpoint = "sts.cn-beijing.aliyuncs.com";
//		String accessKeyId = "LTAI4G1bz51pdFtTcFMiKKcJ";
//		String accessKeySecret = "4Dl6ebWixiFdYOoIsGRXYc2NmPPGnX";
//		String roleArn = "acs:ram::1019871397583127:role/sts-oss";
//		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//		String currentDay = DateUtil.getCurrentDate();
//		Map<String, Object> out = new HashMap<String, Object>();
//		try {
//			// 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
//			DefaultProfile.addEndpoint("", "", "Sts", endpoint);
//			// 构造default profile（参数留空，无需添加region ID）
//			IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
//			// 用profile构造client
//			DefaultAcsClient client = new DefaultAcsClient(profile);
//			final AssumeRoleRequest request = new AssumeRoleRequest();
//			request.setMethod(MethodType.POST);
//			request.setRoleArn(roleArn);
//			request.setRoleSessionName(uuid);
//			// request.setPolicy(policy); // 若policy为空，则用户将获得该角色下所有权限
//			request.setDurationSeconds(1800l); // 设置凭证有效时间
//			final AssumeRoleResponse response = client.getAcsResponse(request);
//			out.put("Expiration", response.getCredentials().getExpiration());
//			out.put("AccessKeyId", response.getCredentials().getAccessKeyId());
//			out.put("AccessKeySecret", response.getCredentials().getAccessKeySecret());
//			out.put("SecurityToken", response.getCredentials().getSecurityToken());
//			out.put("RequestId", response.getRequestId());
//			out.put("uuid", uuid);
//			out.put("currentDay", currentDay);
//			app.setDataSingle(out);
//			return app;
//		} catch (ClientException e) {
//			out.put("Errorcode", e.getErrCode());
//			out.put("Errormessage", e.getErrMsg());
//			out.put("RequestId", e.getRequestId());
//			app.setDataSingle(out);
//			app.NO("");
//		}
//		return app;
//	}
	
	/**
	 * 上传文件
	 *
	 * @throws
	 */
	@SuppressWarnings("unused")
	@ResponseBody
	@RequestMapping(value = "/ossUploadImage")
	public Map<String, Object> uploadImage(@RequestParam("file") MultipartFile file) {
		String bucketName = env.getProperty("lximage.bucketname");
		String fileShow = env.getProperty("oss.call.app.url");
		
		//OSSClient client = new OSSClient("key", "secret");
		String nginxImg = "";
		try {
			String filename = file.getOriginalFilename(); // 文件名
			String ext = filename.substring((filename.lastIndexOf(".")+1),filename.length()).toLowerCase();
			String uploadPath = "videos"; // 图片路径
			if(this.checkIconType(filename)){//图片
				uploadPath = "images";;
			}

			long filenames = System.currentTimeMillis() + new Random().nextInt(10000); // 判断文件
			if (file == null) {
				return null;
			} // 文件路径
			InputStream is = file.getInputStream(); // 文件名
			String fileName = file.getName(); // 文件大小
			Long fileSize = file.getSize(); // 创建上传Object的Metadata
			ObjectMetadata metadata = new ObjectMetadata(); // 上传的文件的长度
			metadata.setContentLength(is.available()); // 指定该Object被下载时的网页的缓存行为
			metadata.setCacheControl("no-cache"); // 指定该Object下设置Header
			metadata.setHeader("Pragma", "no-cache"); // 指定该Object被下载时的内容编码格式
			metadata.setContentEncoding("utf-8");
			// 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
			// 如果没有扩展名则填默认值application/octet-stream
			metadata.setContentType(getContentType(filename));
			// 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
			metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte."); // 上传文件
																										// (上传文件流的形式)
			String originalName = filenames + "." + ext;
			String url = uploadPath + "/" + DateUtil.format(new Date(), "yyyy-MM") + "/" + originalName;
			PutObjectResult putResult = ossClient.putObject(bucketName, url, is, metadata);

			Map<String, Object> resut = new HashMap<>();
			resut.put("code", 0);
			resut.put("url", url);
			resut.put("original",nginxImg+url);
			return resut;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 通过文件名判断并获取OSS服务文件上传时文件的contentType
	 * 
	 * @param fileName
	 *            文件名
	 * @return 文件的contentType
	 */
	public static String getContentType(String fileName) { // 文件的后缀名
		String fileExtension = fileName.substring(fileName.lastIndexOf("."));
		if (".bmp".equalsIgnoreCase(fileExtension)) {
			return "image/bmp";
		}
		if (".gif".equalsIgnoreCase(fileExtension)) {
			return "image/gif";
		}
		if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
				|| ".png".equalsIgnoreCase(fileExtension)) {
			return "image/jpeg";
		}
		if (".html".equalsIgnoreCase(fileExtension)) {
			return "text/html";
		}
		if (".txt".equalsIgnoreCase(fileExtension)) {
			return "text/plain";
		}
		if (".vsd".equalsIgnoreCase(fileExtension)) {
			return "application/vnd.visio";
		}
		if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
			return "application/vnd.ms-powerpoint";
		}
		if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
			return "application/msword";
		}
		if (".xml".equalsIgnoreCase(fileExtension)) {
			return "text/xml";
		} // 视频
		if (".rmvb".equalsIgnoreCase(fileExtension)) {
			return "application/vnd.rn-realmedia-vbr";
		}
		if (".avi".equalsIgnoreCase(fileExtension)) {
			return "video/avi";
		}
		if (".rv".equalsIgnoreCase(fileExtension)) {
			return "video/vnd.rn-realvideo";
		}
		if (".wmv".equalsIgnoreCase(fileExtension)) {
			return "video/x-ms-wmv";
		}
		if (".movie".equalsIgnoreCase(fileExtension)) {
			return "video/x-sgi-movie";
		}
		if (".mp4".equalsIgnoreCase(fileExtension) || "m4e".equalsIgnoreCase(fileExtension)) {
			return "video/mpeg4";
		}
		if (".asf".equalsIgnoreCase(fileExtension) || "asx".equalsIgnoreCase(fileExtension)) {
			return "video/x-ms-asf";
		}
		if (".mpe".equalsIgnoreCase(fileExtension) || "mps".equalsIgnoreCase(fileExtension)) {
			return "video/x-mpeg";
		}
		if (".mp2v".equalsIgnoreCase(fileExtension) || "mpv2".equalsIgnoreCase(fileExtension)) {
			return "video/mpeg";
		}
		if (".mpg".equalsIgnoreCase(fileExtension) || "mpeg".equalsIgnoreCase(fileExtension)
				|| "mpv".equalsIgnoreCase(fileExtension)) {
			return "video/mpg";
		}
		// 默认返回类型
		return "image/jpeg"; 
	}


}
